package prueba;
import nu.xom.*;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class XPathQuery {

  public static void main(String[] args) {
   
   if (args.length == 0) {
     System.err.println("Usage: java XPathQuery url");
     return;
   }      

   String pageURL = args[0];
   
   Builder builder = new Builder();
   try {
     Document tmpdoc = builder.build(pageURL,null);
     XPathContext context = new XPathContext("html", "http://www.w3.org/1999/xhtml");

     Nodes items = tmpdoc.query("//html:div[@class='itemAutos']", context);
     Element root = new Element("root");	 
     for (int i = 0; i < items.size(); i++) {
    	 root.appendChild(items.get(i).copy());
//    	 Element item = (Element)items.get(i);
//    	 System.out.println(i+"- "+(item).getChildElements().get(0).getChildElements().get(0).getValue());
//    	 Elements divsChildren = item.getChildElements(); 
//    	 for (int j = 0; j < divsChildren.size(); j++) {
//    		 System.out.println(": "+divsChildren.get(j).getLocalName());			
//		}
     }
     Document doc = new Document(root);
     try {
         OutputStream out = new FileOutputStream("lanacion_parcial.xml");
         out = new BufferedOutputStream(out);
         Serializer serializer 
          = new Serializer(out, "ISO-8859-1");
         serializer.write(doc);
     }  
     catch (IOException ex) {
         System.err.println("This shouldn't happen for Latin-1!");
     }

    // System.out.println(doc.toXML());
   }
   catch (NullPointerException ex) {
     System.err.println(pageURL + " does not have a title.");     
   }
   catch (ParsingException ex) {
     System.err.println(pageURL + " is malformed.");
     
   }
   catch (IOException ex) {
     System.err.println("Could not read " + pageURL); 
   }  
    
  }
  
}